using UnityEngine;
using System.Collections;

/// \class  gkTextureAnimation
/// \brief  Animate a texture
[AddComponentMenu("GK/Engine/Core/Animation/Texture/gkTextureAnimation")]
public class gkTextureAnimation : MonoBehaviour 
{
	/// The animation texture sequence
	public Texture[] AnimationTexturesSequence;
	
	/// The animation rate in frame per second
	public float RateFramePerSecond = 24.0f;
	
	/// The animation end event notification count
	// < 0 = Infinite
	// 0 = No notification
	// > 0 = number of notification
	public int EndAnimationEventCount = 0;
	
	/// The animation end event
	public string EndAnimationEventName = "";
	
	/// The time since the last frame
	private float m_fTimeSinceLastFrame;
	
	/// The current frame index
	private int m_iCurrentFrameIndex;
	
	/// The event component
	private gkEventComponent m_rEventComponent;
	
	/// \brief  Called just after the game begin to play
	void Start()
	{
		// Set the first texture
		m_iCurrentFrameIndex = 0;
		renderer.material.mainTexture = AnimationTexturesSequence[m_iCurrentFrameIndex];
		
		// Grab the event component
		m_rEventComponent = GetComponent<gkEventComponent>();
	}
	
	/// \brief Update is called once per frame
	void Update ()
	{
		float fDisplayPeriod;
		
		// Update time
		m_fTimeSinceLastFrame += Time.deltaTime;
		
		// If we wait enough time we pass to the next frame
		fDisplayPeriod = 1.0f/RateFramePerSecond;
		if(m_fTimeSinceLastFrame >= fDisplayPeriod)
		{
			m_fTimeSinceLastFrame %= fDisplayPeriod;
			
			// Change the image			
			m_iCurrentFrameIndex = (m_iCurrentFrameIndex + 1) % AnimationTexturesSequence.Length;
			renderer.material.mainTexture = AnimationTexturesSequence[m_iCurrentFrameIndex];
			
			// if we have to notify of the animation end
			if(EndAnimationEventCount != 0)
			{
				// If we are at the last image fire an event
				if(m_iCurrentFrameIndex >= (AnimationTexturesSequence.Length-1))
				{
					m_rEventComponent.RaiseEvent(EndAnimationEventName);
					if(EndAnimationEventCount > 0)
					{
						EndAnimationEventCount--;	
					}
				}
			}
		}
	}
}
